from functools import reduce
def f(x):
    return x*x
r = map(f,[1,2,3,4,5,6,7]) # 传入一个函数名和iterable 返回一个iterator
print(r)
for x in r:
    print(x)

ret = map(len,[[1],[123,123,123],[1,2]])
for x in ret:
    print(x)

print("============================================================")
def add(x,y):
    return x + y
def div(x,y):
    return x * y
ret = reduce(add,[1,3,5,7,8])
ret = reduce(lambda x, y : x * y,[1,3,5,7,8])
print(ret)
ret = reduce(div,list(range(1,10)))
print(ret)

def fn(x,y):
    return x*10 + y
ret = reduce(fn,[1,3,5,7]) # 变成整数1357
print(ret)
print("============================================================")
# 将str变成int
def char2num(s):
    digits = {"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9}
    return digits[s]
print(map(char2num,"1234"))
for x in (map(char2num,"1234")):
    print(x)

ret = reduce(fn,map(char2num,"1234"))
print(ret)

print("===================practice1=========================================")
def normalize(name):
    return name[0].upper() + name[1:].lower()

# 测试:
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)

print("===================practice2=========================================")
def prod(L):
    return reduce(lambda x,y:x*y,L)

print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
    print('测试成功!')
else:
    print('测试失败!')


print("===================practice3=========================================")

def str2float(s):
    i,f = s.split('.')
    i_number = reduce(lambda x , y: x * 10 + y , map(int,i))
    f_number = reduce(lambda x , y: x * 10 + y , map(int,f)) / 10**len(f)
    return i_number + f_number



print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
    print('测试成功!')
else:
    print('测试失败!')






























